//
//  MatchViewController.m
//  YouthOlympic2014
//
//  Created by xiangpaopao on 14-6-20.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "MatchViewController.h"
#import "TimeLineCell.h"
#import "TimeLineListHeaderView.h"
#import "UIButton+Property.h"
#import "WeiboViewController.h"
#import "DayCell.h"
#import "AlertService.h"
#import "AppDelegate.h"
#import "GameService.h"
#import "GameEvent.h"

@interface MatchViewController ()

@end

@implementation MatchViewController
@synthesize timeline,keys;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.eventListViewOffset = 50;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([theApp isAppReachable]) {
        [self updateMainDataAndViewByDate:[NSString stringWithFormat:@"201408%ld",(long)[AppUtils getCurDayInYogRange]] isFirstLoad:YES];
        [self updateDateMarks];
    }

    
}


- (void)updateMainDataAndViewByDate:(NSString*)date isFirstLoad:(BOOL)first
{
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    self.HUD.labelText = nil;
    [self.HUD show:YES];
    //NSLog(@"date is %@",date);
    [[[GameService alloc] init] getGameEventsDictByGameId:@""
                                             andSubGameId:@""
                                                  andDate:date
                                               completion:^(id result, NSError *error) {
                                                   [self.HUD hide:YES];
                                                   if (error == nil && [result count] != 0) {
                                                       self.timeline = result;
                                                       self.keys = [[self.timeline allKeys] sortedArrayUsingSelector:@selector(compare:)];
                                                       NSLog(@"self.timeline %@",[AppUtils replaceUnicodeDic:self.timeline]);

                                                       NSLog(@"self.keys %@",self.keys);
                                                   }else{
                                                       //TODO
                                                       self.timeline = nil;
                                                       self.keys = nil;
                                                   }
                                                   [self reloadEventData];
                                                   if (first) {
                                                       [self initSelectedDay];
                                                   }
    }];
    
    //天气
    [[[WeatherService alloc] init] getWeather:date
                                   completion:^(id result, NSError *error) {
                                       if (error == nil) {
                                           [self.weatherLb setText:result];
                                           NSLog(@"result is %@",result);
                                       }else{
                                           [self.weatherLb setText:@""];
                                       }
                                   }];
    
}

-(void)updateDateMarks
{
    //self.HUD.mode = MBProgressHUDModeIndeterminate;
    //[self.HUD show:YES];
    [[[CalendarMarkService alloc] init] getDaysByGameType:@""
                                           andGameSubType:@""
                                               completion:^(id result, NSError *error) {
        //[self.HUD hide:YES];
    
        if (nil == error) {
            self.dateMarks = result;
            [self reloadCalendarData];
            
        }else{
            //TODO
        }
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


- (IBAction)followAction:(id)sender
{
    UIButton *btn = sender;
    
    if (!btn.selected) {
        self.HUD.mode = MBProgressHUDModeText;
        self.HUD.labelText = NSLocalizedString(@"已添加到关注", nil);
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:1.1];
        
        GameEvent *event = (GameEvent*)[btn.property valueForKey:@"event"];
        NSIndexPath *indexPath = (NSIndexPath*)[btn.property valueForKey:@"indexPath"];
        //更新数据
        NSString* key = self.keys[indexPath.section];
        event.stared = YES;
        self.timeline[key][indexPath.row] = event;
        
        [[[GameService alloc] init] addGameEventToSchedule:event];
        //添加到提醒
        [[[AlertService alloc] init] addNotificationForEvent:event];
        //[btn setSelected:YES];
        [self.eventListView reloadData];
    }
    
}
- (IBAction)shareAction:(id)sender
{
    WeiboViewController *weiboCtrl = [self.storyboard instantiateViewControllerWithIdentifier:@"weiboCtrl"];
    [self.navigationController pushViewController:weiboCtrl animated:YES];
}


#pragma mark - collectionView delegate & datasource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [super collectionView:collectionView didSelectItemAtIndexPath:indexPath];
    if ([theApp isAppReachable]) {
        [self updateMainDataAndViewByDate:[NSString stringWithFormat:@"201408%@",[self.dayArr objectAtIndex:indexPath.row]] isFirstLoad:NO];
    }
}

#pragma mark - TableView delegate & datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.timeline allKeys].count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    NSString* key = self.keys[section];
    NSArray* nameSection = self.timeline[key];
    return nameSection.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TimeLineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"timeLineCell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        [cell.line setHidden:YES];
    }
    
    NSString* key = self.keys[indexPath.section];
    NSArray* events = self.timeline[key];
    GameEvent* event = events[indexPath.row];
    //
    cell.titleLabel.text = event.title;
    cell.locationLabel.text = [NSString stringWithFormat:@"at.%@", event.place];
    cell.icon.image = event.icon;
    
    //通过setProperty给按钮传递数据，通过setSelected控制按钮是否显示已关注
    [cell.followBtn setSelected:event.stared];
  
    NSDictionary *property = [[NSDictionary alloc] initWithObjectsAndKeys:event,@"event",indexPath,@"indexPath", nil];
    [cell.followBtn setProperty:property];
    
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *xibContents = [[NSBundle mainBundle] loadNibNamed:@"TimeLineListHeaderView" owner:self options:nil];
    TimeLineListHeaderView *customView = [xibContents lastObject]; //safer than objectAtIndex:0
    
    [customView.timeLabel setText:self.keys[section]];
    return customView;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40.0;
}

@end
